// ColorSegment-Make.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

#include <cv.h>
#include <highgui.h>

#define MAXTYPE 3
using namespace cv;


char	foodname[10][255] = { "carrot","corn","greenpea","cookedwhiterice"};
int		color[10][3] = { {255,127,39}, {255,255,0} , {0,128,0}, {255,255,176} , {0,0,0},{255,255,255},{127,127,127}};
MatND	foodColorHist[10]; 
char	filename[255];
int		scale=10;
int		hbins = 30, sbins = 32;

int _tmain(int argc, _TCHAR* argv[])
{
	for(int i=0;i<MAXTYPE;i++)
	{
		foodColorHist[i] = cvCreateMat(hbins,sbins,CV_32FC1);
		sprintf(filename,"D:\\pawfood\\ColorSegment\\Data\\color\\%s.txt",foodname[i]);
		FILE *fp = fopen(filename,"r");
		for( int h = 0; h < hbins; h++ )
			for( int s = 0; s < sbins; s++ )
			{
				float v;
				fscanf(fp,"%f",&v);
				foodColorHist[i].at<float>(h, s) = v;
			}
		fclose(fp);
	}

	for(int i=1;i<=21;i++)
	{
		sprintf(filename,"D:\\color-sample\\friedrice\\%d.jpg",i);
		Mat src, hsv;
		src=imread(filename);
		cvtColor(src, hsv, CV_BGR2HSV);
		int h,s;
		Mat_<Vec3b>& img = (Mat_<Vec3b>&)hsv;
		Mat markImg = Mat::zeros(hsv.rows, hsv.cols, CV_8UC3);
		for(int y=0;y<hsv.rows;y++)
		{
			for(int x=0;x<hsv.cols;x++)
			{
				 h = img(y,x)[0];
				 s = img(y,x)[1];
				 int hindex = h/6;
				 int sindex = s/8;
				 // paint the maximun possible color]
				 float maxHS=0.0f;
				 int	maxCategory=-1;
				 float  sumCat=0.0f;
				 for(int j=0;j<MAXTYPE;j++)
				 {
					 float p = foodColorHist[j].at<float>(hindex, sindex);
					 sumCat+=p;
					 if( p > maxHS)
					 {
						 maxHS = p;
						 maxCategory=j;
					 }
				 }
				 //if(maxHS/sumCat < 0.75)
				 //{
					//  maxCategory=5;
				 //}
				 if(maxCategory==-1) 
					 maxCategory=4;
				 rectangle( markImg, Point(x, y),
									Point(x, y),
									Scalar(color[maxCategory][2],color[maxCategory][1],color[maxCategory][0]),
									CV_FILLED );
				 //markImg.at<uchar>(hindex,sindex)[0] = color[maxCategory][0];
				// markImg.at<uchar>(hindex,sindex)[1] = color[maxCategory][1];
				 //markImg.at<uchar>(hindex,sindex)[2] = color[maxCategory][2];
			}
		}
		namedWindow( "markImg", 1 );
		imshow( "markImg", markImg );
		sprintf(filename,"friedriceMask\\%d.jpg",i);
		imwrite(filename,markImg);

		namedWindow( "src", 1 );
		imshow( "src", src );
		//waitKey();
	}

	cout << "CAT" << endl;
	return 0;
}

